package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.ExceptionLogMapper;
import com.itheima.pojo.*;
import com.itheima.service.ExceptionLogService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import java.text.ParseException;
import java.util.List;

@Service
public class ExceptionLogServiceImpl implements ExceptionLogService {

    @Autowired
    private ExceptionLogMapper exceptionLogMapper;

    @Override
    public PageResult getExceptionList(ExceptionLogVO exceptionLogVO) {

        PageHelper.startPage( exceptionLogVO.getCurrentPage(),10);

        Example example = createExample(exceptionLogVO);
        List<ExceptionLog> exceptionLogList= exceptionLogMapper.selectByExample(example);

        PageInfo pageInfo = new PageInfo<>(exceptionLogList);

        List list = pageInfo.getList();

        long total = pageInfo.getTotal();

        return new PageResult(total,list);
    }

    /*
     * 封装查询条件对象*/
    private Example createExample(ExceptionLogVO exceptionLogVO)  {
        Example example = new Example(ExceptionLog.class);
        Example.Criteria criteria = example.createCriteria();
        if (!"".equals(exceptionLogVO.getStartTime())&&exceptionLogVO.getStartTime()!=null) {

            //startTime: "Wed Apr 01 2020 00:00:00 GMT+0800 (中国标准时间),Fri May 01 2020 00:00:00 GMT+0800 (中国标准时间)"
            String startTime2 = exceptionLogVO.getStartTime();
            String replace = startTime2.replace("(中国标准时间)", "");
            String[] split = replace.split(",");
            if (split.length > 0){
                String s1 = split[0];
                String startTime = null;
                try {
                    startTime = DateUtils.getDateTime(s1);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                String s2 = split[1];
                String endTime = null;
                try {
                    endTime = DateUtils.getDateTime(s2);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                // 根据时间范围查询  起始时间---截至时间

                criteria.andBetween("updateTime",startTime,endTime);
            }

        }
        return example;
    }
}
